package com.module.ad.tengxun;

import android.app.Activity;
import android.util.Log;

import com.module.privacy.module_ad.LogADUtils;
import com.qq.e.ads.nativ.NativeADUnifiedListener;
import com.qq.e.ads.nativ.NativeUnifiedAD;
import com.qq.e.ads.nativ.NativeUnifiedADData;
import com.qq.e.comm.util.AdError;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * draw信息流
 */
public class TXDrawAd {
    private final static int count = 3;
    private static final String TAG = "腾讯广告";

    /**
     * 向list 插入广告、、加载是异步，需要改成同步。所以使用CountDownLatch。
     *
     * @param indexs 广告需要插入的位置。如[5,10,15] 分别插入5、10、15的位置
     */
    public static List loadDrawAd(Activity context, String posId, List list, int[] indexs) {
        LogADUtils.d(TAG, "启动腾讯流广告");

        CountDownLatch controller = new CountDownLatch(count);

        NativeUnifiedAD mAdManager = new NativeUnifiedAD(context, posId, new NativeADUnifiedListener() {
            @Override
            public void onADLoaded(List<NativeUnifiedADData> listAd) {
                //数据为空
                if (listAd == null) {
                    for (; ; ) {
                        controller.countDown();
                        if (controller.getCount() <= 0) {
                            break;
                        }
                    }
                }
                //添加广告数据
                for (int i = 0; i < listAd.size(); i++) {
                    final int finalI = i;
                    NativeUnifiedADData ad = listAd.get(finalI);
                    LogADUtils.d(TAG, "腾讯流广告加载成功" + ad.getAdPatternType());
                    int index = indexs[finalI];
                    if (list.size() > index) {
                        list.add(index, ad);
                    }
                    controller.countDown();
                }
            }

            @Override
            public void onNoAD(AdError adError) {
                LogADUtils.d(TAG, "腾讯流广告加载失败" + adError.getErrorMsg());
                for (; ; ) {
                    controller.countDown();
                    if (controller.getCount() <= 0) {
                        break;
                    }
                }
            }
        });
        mAdManager.setMinVideoDuration(0);
        mAdManager.setMaxVideoDuration(0);
        mAdManager.loadData(count);
        return list;

    }
}
